import { WebSocket, WebSocketServer } from 'ws';
import Logger from './log';

interface MsgType {
    type: string,
    params: string
}

class WebServer {
    private handlers: Map<string, (e: MsgType) => void>;
    private server: WebSocketServer | null;
    // 存储所有连接的客户端
    private webSockets: Set<WebSocket>;

    public constructor(host: string, port: number) {
        this.handlers = new Map<string, (e: MsgType) => void>();
        this.webSockets = new Set<WebSocket>();
        this.server = new WebSocketServer({ host: 'localhost', port: 3000 });
        Logger.Message(`Server: 'ws://${host}:${port}'`);

        // 监听客户端连接
        this.server.on('connection', (ws: WebSocket) => {
            Logger.Message(`New client is connected.`);
            // 发送欢迎消息给新连接的客户端
            ws.send(JSON.stringify({type: 'reply', params: 'successfully'}));

            // 监听客户端发送的消息
            ws.on('message', (data: Buffer) => {
                try {
                    const message = data.toString();
                    Logger.Message(`收到客户端消息：${message}`);

                    // 解析客户端消息（假设为 JSON 格式）
                    const info = JSON.parse(message) as MsgType;

                    // 回复当前客户端
                    ws.send(JSON.stringify({
                        type: 'reply',
                        params: `服务器已收到：${info.params}`
                    }));
                } catch (err) {
                    Logger.Message(`消息处理错误：${err}`);
                    ws.send(JSON.stringify({
                        type: 'error',
                        params: '无效的消息格式'
                    }));
                }
            });

            // 监听客户端断开连接
            ws.on('close', () => {
                Logger.Message('客户端断开连接');
                this.webSockets.delete(ws);
            });

            // 监听错误
            ws.on('error', (err: any) => {
                Logger.Message('WebSocket 错误：', err);
            });

            this.webSockets.add(ws);
        });

        // 服务器错误处理
        this.server.on('error', (err: any) => {
            Logger.Message('服务器错误：', err);
        });

    }

    public Close(): void {
        this.server?.close();
    }

    // 广播消息给所有客户端
    public Broadcast(data: string) {
        this.webSockets.forEach((ws) => {
            if (ws.readyState === WebSocket.OPEN) {
                ws.send(data);
            }
        });
    };

    public RegisterHandler(type: string, handler: (e: MsgType) => void) {
        this.handlers.set(type, handler);
    }

    public ProcessMessages(message: MsgType) {
        const handler = this.handlers.get(message.type);
        if (handler) {
            handler(message);
        }
    }

    public Send(message: MsgType) {
    }
}

export default WebServer;